﻿
using FreesenseSubAIS.ImageProcess;
using FreesenseSubAIS.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Telerik.WinControls.Enumerations;
using Telerik.WinControls.UI;

namespace FreesenseSubAIS.UI
{
    public partial class configForm : RadForm
    {
        ProjectParam curentP;
        string[] standList = { "standard.bmp", "red.bmp", "green.bmp", "blue.bmp", "black.bmp", "white.bmp", "gray.bmp", "flicker.bmp", "hrows.bmp", "hcolumns.bmp", "vrows.bmp", "vcolumns.bmp", "lowuiflicker.bmp", "lowuiuniformity.bmp" };
        double[] exposeList = { 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000 };
        DataTable dt = new DataTable();
        //支持检测图片格式
        string[] PicFormat = { ".png", ".jpg", ".bmp" };
        public configForm()
        {
            InitializeComponent();
            dt.Columns.Add("pictureName");
            dt.Columns.Add("exposeTime");
            dt.Columns[0].DataType = typeof(string);
            dt.Columns[1].DataType = typeof(int);
        }

        private void CameraForm_Load(object sender, EventArgs e)
        {
            try
            {
                RefreshDevicePara(Device.Parameter);
                //RefreshCurrentProduct();
                RefreshProductList();
                isExtatPicsRCB.Checked = Device.SaveSourceImage;
                SaveNGpic_Cbox.Checked = Device.Parameter.SaveNgImage;
                SaveInsp_Cbox.Checked = Device.Parameter.SaveInspImage;
                //ShotMode_cbx.Checked = ImageManage.Instance.OnlyShotPic;
                if (Device.Automode)
                    AutoMode_radb.Checked = true;
                else
                    DebugMode_radb.Checked = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 保存参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveBtn_Click(object sender, EventArgs e)
        {
            try
            {
                UpdataUIPara();
                Device.SaveParameter();
                MessageBox.Show("参数保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void setDefaultBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (radListControl1.SelectedIndex == -1)
                    return;
                Device.Parameter.DefaultProductId = radListControl1.Items[radListControl1.SelectedIndex].ToString();
                DefaultPrductTB.Text = Device.Parameter.DefaultProductId;
                MessageBox.Show("本地默认设置成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("本地默认设置失败！请手动配置主机默认产品！", "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        public void RefreshProductList()
        {
            radListControl1.Items.Clear();
            List<string> list = ProductManager.GetExistProduct();
            if (list != null && list.Count > 0)
            {
                radListControl1.Items.AddRange(list.ToArray());
                int a = radListControl1.Items.IndexOf(Device.Parameter.DefaultProductId);
                if (a > -1)
                    radListControl1.SelectedIndex = a;
            }
        }
        public void RefreshCurrentProduct()
        {
            radListControl1.Items.Clear();
            List<string> list = ProductManager.GetExistProduct();
            if (list != null && list.Count > 0)
            {
                var f = list.Find(item => item.Contains(Device.defaultProduct.ProductName));
                if (f == null)
                {
                    list.Add(Device.defaultProduct.ProductName);
                }

                radListControl1.Items.AddRange(list.ToArray());
                int a = radListControl1.Items.IndexOf(Device.Parameter.DefaultProductId);
                if (a > -1)
                    radListControl1.SelectedIndex = a;
            }
            else
                list.Add(Device.defaultProduct.ProductName);
        }
        public void RefreshDevicePara(DeviceParameter dp)
        {
            subindex_cbx.Text = dp.Subindex.ToString();
            dustLightupComRTB.Text = dp.DustLightCom;
            DefaultPrductTB.Text = dp.DefaultProductId;
            BackLightComRTB.Text = dp.BackLightCom;
            dustLightdownComRTB.Text = dp.DustLightDownCom;
            IOComTx.Text = dp.IOCardComName;
            ChannelTx.Text = dp.IOODownSwitchPic.ToString ();
            PowerChannelTx.Text = dp.SideLight1Channle.ToString ();

        }
        public void UpdataUIPara()
        {
            Device.Parameter.DustLightCom = dustLightupComRTB.Text.Trim();
            Device.Parameter.BackLightCom = BackLightComRTB.Text.Trim();
            Device.Parameter.IOCardComName   = IOComTx.Text.Trim();
            Device.Parameter.DustLightDownCom = dustLightdownComRTB.Text.Trim();
            Device.Parameter.Subindex = Convert.ToInt32(subindex_cbx.Text.Trim());
            Device.Parameter.IOODownSwitchPic = Convert.ToByte(ChannelTx.Text.Trim());
            Device.Parameter.SideLight1Channle  = Convert.ToByte(PowerChannelTx.Text.Trim());
        }

        private void configForm_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void DelProRBtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var sele = radListControl1.SelectedItem;
                if (sele != null)
                {
                    ProductManager.DeleteProduct((string)sele.Text);
                    if (sele.Text == Device.Parameter.DefaultProductId)
                    {
                        Device.Parameter.DefaultProductId = "";
                        Device.SaveParameter();
                    }
                    RefreshProductList();
                    MessageBox.Show("删除产品成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void newProductRBtn_Click(object sender, EventArgs e)
        {
            TextInputForm tif = new TextInputForm("请输入产品名称", "新建产品");
            tif.ShowDialog();
            if (tif.IsConform)
            {
                for (int i = 0; i < radListControl1.Items.Count; i++)
                {
                    if (radListControl1.Items[i].Text.Trim() == tif.InputString)
                    {
                        MessageBox.Show("输入的名称已存在,请重新输入!", "新建产品失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                ProductManager.NewProdect(tif.InputString);
                RefreshProductList();
                MessageBox.Show("新建产品成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void directoryCopy(string sourceDirectory, string targetDirectory)
        {
            try
            {
                if (!Directory.Exists(sourceDirectory))
                {
                    return;
                }
                if (!Directory.Exists(targetDirectory))
                {
                    Directory.CreateDirectory(targetDirectory);
                }
                DirectoryInfo sourceInfo = new DirectoryInfo(sourceDirectory);
                FileInfo[] fileInfo = sourceInfo.GetFiles();
                foreach (FileInfo fiTemp in fileInfo)
                {
                    string p = Path.GetExtension(sourceDirectory + fiTemp);
                    if (PicFormat.Contains(p.ToLower()))
                    {
                        File.Copy(sourceDirectory + "\\" + fiTemp.Name, targetDirectory + "\\" + fiTemp.Name);
                    }
                }
                #region 移动路径下所有文件夹
                //DirectoryInfo[] diInfo = sourceInfo.GetDirectories();
                //foreach (DirectoryInfo diTemp in diInfo)
                //{
                //    string sourcePath = diTemp.FullName;
                //    string targetPath = diTemp.FullName.Replace(sourceDirectory, targetDirectory);
                //    Directory.CreateDirectory(targetPath);
                //    directoryCopy(sourcePath, targetPath);
                //}
                #endregion 移动路径下所有文件夹
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void copyRBtn_Click(object sender, EventArgs e)
        {
            var sele = radListControl1.SelectedItem;
            if (sele != null)
            {
                string oldname = (string)sele.Text;
                TextInputForm tif = new TextInputForm("请输入复制品名称", "复制产品");
                tif.ShowDialog();
                if (tif.IsConform)
                {
                    for (int i = 0; i < radListControl1.Items.Count; i++)
                    {
                        if (radListControl1.Items[i].Text.Trim() == tif.InputString)
                        {
                            MessageBox.Show("输入的名称已存在！", "复制产品失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    ProjectParam souce = ProductManager.OpenProduct(sele.Text);
                    ProjectParam des = ProductManager.CloneProduct(souce);
                    des.ProductName = tif.InputString;
                    ProductManager.SaveProduct(des);
                    SystemCommon.CopyConfigFile(Path.Combine(Device.ProjectPath, tif.InputString, string.Format("{0}_AIS.xls", tif.InputString)), Path.Combine(Device.ProjectPath, oldname, string.Format("{0}_AIS.xls", oldname)));
                    SystemCommon.CopyConfigFile(Path.Combine(Device.ProjectPath, tif.InputString, string.Format("{0}_list_vcom.xls", tif.InputString)), Path.Combine(Device.ProjectPath, oldname, string.Format("{0}_list_vcom.xls", oldname)));
                    directoryCopy(Path.Combine(Device.ProjectPath, oldname, "MoudlImgs"), Path.Combine(Device.ProjectPath, tif.InputString, "MoudlImgs"));
                    RefreshProductList();
                    MessageBox.Show("复制成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void ReNameProRBtn_Click(object sender, EventArgs e)
        {
            var sele = radListControl1.SelectedItem;
            if (sele != null)
            {
                string oldname = (string)sele.Text;
                TextInputForm tif = new TextInputForm("请输入新名称", "重命名产品");
                tif.ShowDialog();
                if (tif.IsConform)
                {
                    for (int i = 0; i < radListControl1.Items.Count; i++)
                    {
                        if (radListControl1.Items[i].Text.Trim() == tif.InputString)
                        {
                            MessageBox.Show("输入的名称已存在,请重新输入!", "重命名产品失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    SystemCommon.ReNameConfigFile(string.Format("{0}_AIS.xls", tif.InputString), Path.Combine(Device.ProjectPath, oldname, string.Format("{0}_AIS.xls", oldname)));
                    SystemCommon.ReNameConfigFile(string.Format("{0}_list_vcom.xls", tif.InputString), Path.Combine(Device.ProjectPath, oldname, string.Format("{0}_list_vcom.xls", oldname)));
                    ProductManager.ReNameProduct(oldname, tif.InputString);
                    RefreshProductList();
                    MessageBox.Show("重命名成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void radListControl1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            if (radListControl1.Items.Count > 0 && radListControl1.SelectedIndex != -1)
            {
                curentP = ProductManager.OpenProduct(radListControl1.Items[radListControl1.SelectedIndex].ToString());
                if (curentP != null)
                {
                    backLightBrightRTB.Text = curentP.Intensity.BackLight.ToString();
                    sideLupBrightRTB.Text = curentP.Intensity.SideLightUp.ToString();
                    sideLdownBrightRTB.Text = curentP.Intensity.SideLightDown.ToString();
                    setParameterControl1.LoadProduct(curentP);
                }
                else
                {
                    curentP = new ProjectParam { ProductName = radListControl1.Items[radListControl1.SelectedIndex].ToString() };
                    MessageBox.Show("未找到程序文件！");
                }
            }
        }

        private void OpenUpSl_RBtn_Click(object sender, EventArgs e)
        {
            byte inten = 0;
            var s = sender as RadButton;
            if (s.Name.ToLower().Contains("up"))
            {
                if (byte.TryParse(sideLupBrightRTB.Text, out inten))
                    Device.DeviceEntityControl.OpenUpSideLight(inten);
            }
            else
            {
                if (byte.TryParse(sideLdownBrightRTB.Text, out inten))
                    Device.DeviceEntityControl.OpenDownSideLight(inten);
            }
        }

        private void CloseUpSl_RBtn_Click(object sender, EventArgs e)
        {
            var s = sender as RadButton;
            if (s.Name.ToLower().Contains("up"))
                Device.DeviceEntityControl.CloseUpSideLight();
            else
                Device.DeviceEntityControl.CloseDownSideLight();
        }

        private void openBackLightRBtn_Click(object sender, EventArgs e)
        {
            byte inten = 0;
            if (byte.TryParse(backLightBrightRTB.Text, out inten))
                Device.DeviceEntityControl.OpenBackLight(inten);
        }

        private void closeBackLightRbtn_Click(object sender, EventArgs e)
        {
            Device.DeviceEntityControl.CloseBackLight();
        }


        private void save2RBtn_Click(object sender, EventArgs e)
        {
            // curentP.AlthPara = athpara;
            ProductManager.SaveProduct(curentP);
            SaveBtn_Click(null, null);
        }

        private void isExtatPicsRCB_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            Device.SaveSourceImage = isExtatPicsRCB.Checked;
        }

        private void CameraConfig_Btn_Click(object sender, EventArgs e)
        {
            CameraSet CSForm = CameraSet.Entrance();
            CSForm.ShowDialog();
        }

        private void SaveInsp_Cbox_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            Device.Parameter.SaveInspImage = SaveInsp_Cbox.Checked;
        }
        private void SaveNGpic_Cbox_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            Device.Parameter.SaveNgImage = SaveNGpic_Cbox.Checked;
        }
        private void radPageView1_SelectedPageChanged(object sender, EventArgs e)
        {
            backLightBrightRTB.Text = curentP.Intensity.BackLight.ToString();
            sideLupBrightRTB.Text = curentP.Intensity.SideLightUp.ToString();
            sideLdownBrightRTB.Text = curentP.Intensity.SideLightDown.ToString();
        }

        private void BackXml_Btn_Click(object sender, EventArgs e)
        {
            ProductManager.BackUpPara(curentP);
        }

        private void ReadXML_Btn_Click(object sender, EventArgs e)
        {
            curentP = ProductManager.RestoryPara(curentP.ProductName, false);
        }
        private void ReadDeviceXML_Btn_Click(object sender, EventArgs e)
        {
            Device.Parameter = ProductManager.RestoryDevicePara("DeviceParamBackUp");
        }
        private void ReadOldXML_Btn_Click(object sender, EventArgs e)
        {
            curentP = ProductManager.RestoryPara(curentP.ProductName, true);//string.Format("{0}{1}", curentP.ProductName, "_new")
        }
        private void ShotMode_cbx_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            //ImageManage.Instance.OnlyShotPic = ShotMode_cbx.Checked;
        }

        private void AutoMode_radb_CheckedChanged(object sender, EventArgs e)
        {
            Device.Automode = AutoMode_radb.Checked;
        }

        private void DebugMode_radb_CheckedChanged(object sender, EventArgs e)
        {
            Device.Automode = !DebugMode_radb.Checked;
        }

        #region 点灯机手动操作
        private void IOOutputBtn_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex > -1 && comboBox2.SelectedIndex > -1)
            {
                (Device.DeviceEntityControl as DeviceControl0176).IoOutput((byte)(comboBox2.SelectedIndex), (byte)(comboBox1.SelectedIndex));
            }
        }
        private void ChangColorBtn_Click(object sender, EventArgs e)
        {
            Device.DeviceEntityControl.ChangeColor(-1);
        }

        private void PowerOnBtn_Click(object sender, EventArgs e)
        {
            Device.DeviceEntityControl.Begin();
        }
        #endregion 点灯机手动操作


    }
}
